<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>购物车</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <link rel="stylesheet" href="/node_modules/LobsterUIFrame/weui/css/weui.css" />
    <link rel="stylesheet" href="/node_modules/LobsterUIFrame/weui/css/weuix.css" />
    <script src="/node_modules/LobsterUIFrame/weui/js/zepto.min.js"></script>
    <script src="/node_modules/LobsterUIFrame/weui/js/zepto.weui.js"></script>
    <script src="/node_modules/LobsterUIFrame/weui/js/swipe.js"></script>
    <script src="/node_modules/LobsterUIFrame/weui/js/macy.js"></script>
    <script src="/node_modules/LobsterUIFrame/weui/js/php.js"></script>
    <script src="/lobstersdk/lobster.js"></script>
    <script src="/jslib/template-web.js"></script>
    <style>

    </style>
</head>

<body ontouchstart>
    <div class="weui-btn_primary weui-header " style="height: 45px;">
        <div class="weui-header-right" id="edit">编辑</div>
    </div>
    <div id="cartlist">

    </div>
    <div id="half" class='weui-popup__container popup-bottom' style="z-index:501;">
        <div class="weui-popup__overlay"></div>
        <div class="weui-popup__modal">
            <div class="toolbar">
                <div class="toolbar-inner">
                    <a href="javascript:;" class="picker-button close-popup">关闭</a>
                    <h1 class="title">规格</h1>
                </div>
            </div>
            <div class="modal-content" id="modalcontent">
            </div>
        </div>
    </div>
    <div id='tb' class="weui-tab" style="height:auto;">
        <div class="weui-tabbar tab-bottom">
            <a href="../index.html" class="weui-tabbar__item">
                <i class="icon icon-27 f27 weui-tabbar__icon"></i>
                <p class="weui-tabbar__label">商城</p>
            </a>
            <a href="index.html" class="weui-tabbar__item">
                <span style="display: inline-block;position: relative;">
                    <i class="icon icon-28 f27 weui-tabbar__icon"></i>
                    <span id="cartcount" class="weui-badge" style="position: absolute;top: -2px;right: -13px;display: none;">8</span>
                </span>
                <p class="weui-tabbar__label  f-green">购物车</p>
            </a>
            <a href="../mine.html" class="weui-tabbar__item ">
                <i class="icon icon-30 f27 weui-tabbar__icon"></i>
                <p class="weui-tabbar__label ">我的</p>
            </a>
        </div>
    </div>
</body>
<style>
    .bottom {
        background-color: #F5F5F5;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        align-items: center;
        display: flex;
        padding: 10px 4px;
    }

    .weui-btn {
        height: 40px;
        line-height: 40px;
    }
    .price {
            color: #EE5555;
        }

        .price2 {
            margin-left: 20px;
            text-decoration: line-through;
        }
        .weui-label-list .label {
            line-height: 2em;
            height: 2em;
        }
</style>

</html>
<script type="text/template" id="cartlisttemp">
    {{each list item idx}}
    <div class="weui-cells weui-cells_checkbox" style="display:flex;align-items: center;">
            <label class="weui-cell weui-check__label" for="s{{idx}}">
                <div class="weui-cell__hd" >
                    {{if(isEditStatus)}}
                    {{if(item.checked2)}}
                    <input class="weui-check itemcheckbox" data-cartid="{{item.CartId}}" name="checkbox1" id="s{{idx}}" checked type="checkbox">
                    {{else}}
                    <input class="weui-check itemcheckbox" data-cartid="{{item.CartId}}" name="checkbox1" id="s{{idx}}" type="checkbox">
                    {{/if}}
                    {{else}}
                    {{if(item.checked)}} 
                    <input class="weui-check itemcheckbox" data-cartid="{{item.CartId}}" name="checkbox1" id="s{{idx}}" checked type="checkbox">
                    {{else}}
                    <input class="weui-check itemcheckbox" data-cartid="{{item.CartId}}" name="checkbox1" id="s{{idx}}" type="checkbox">
                    {{/if}}
                    {{/if}}
                    <i class="weui-icon-checked"></i>
                </div>
            </label> 
            <div class="weui-cell__hd" style="width:55%;">
                <a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
                    <div class="weui-media-box__hd">
                        <img class="weui-media-box__thumb" src="{{item.GoodsSpecImg}}" alt="">
                    </div>
                    <div class="weui-media-box__bd">
                        <h4 class="weui-media-box__title">{{item.GoodsName}}</h4>
                        <p class="weui-media-box__desc spec" data-item="{{item}}">规格 {{item.SpecName}} <i class="icon icon-6"></i></p>
                        <div class="weui-media-box__desc" style="display: flex;"> ￥{{item.GoodsRetailPrice}}</div>
                    </div>
                </a>
            </div>
            <div class="weui-cell__ft" style="flex: 1;text-align:center;">
                <div class="weui-count" data-idx="{{idx}}">
                    <a class="weui-count__btn weui-count__decrease"></a>
                    <input class="weui-count__number" type="number" value="{{item.Num}}" />
                    <a class="weui-count__btn weui-count__increase"></a>
                </div>
            </div>
        </div>
        {{/each}}
        {{if(list.length==0)}}
        <div style="display:flex;align-items:center;justify-content:center;height: 500px;flex-direction: column;">
        <div style="text-align: center;">购物车空空如也~</div>
        <a style="margin-top:10px;" href="../index.html" class="weui-btn weui-btn_mini weui-btn_plain-primary">去商城逛逛</a> 
        </div>
        {{/if}} 
        <div class="btn" style="position: fixed;bottom: 55px;left: 0; right: 0;">
            <div class="weui-flex">
                <div class="weui-flex__item" style="align-items: center;" id="selectall">
                    <div class="weui-cells weui-cells_checkbox" style="margin-top: 0;">
                        <label class="weui-cell weui-check__label" for="sall">
                            <div class="weui-cell__hd">
                                {{if(isEditStatus)}}
                                {{if(seletedAll2)}}
                                <input class="weui-check" name="checkbox1" id="sall" type="checkbox" checked>
                                {{else}}
                                <input class="weui-check" name="checkbox1" id="sall" type="checkbox">
                                {{/if}}
                                {{else}}
                                {{if(seletedAll)}}
                                <input class="weui-check" name="checkbox1" id="sall" type="checkbox" checked>
                                {{else}}
                                <input class="weui-check" name="checkbox1" id="sall" type="checkbox" >
                                {{/if}}
                                {{/if}}
                                <i class="weui-icon-checked"></i>
                            </div>
                            <div class="weui-cell__bd">
                                <p>全选</p>
                            </div>
                        </label>
                    </div>
                </div>
                <div class="weui-flex__item" style="align-items: center;display: flex;">
                    <label style="margin: auto;" id="totalmoney">金额:￥{{total}}</label>
                    {{if(isEditStatus)}}
                    <a href="javascript:;" class="weui-btn weui-btn_primary removecart"
                        style="width: 100px;border-radius: 0;">删除</a>
                        {{else}}
                        <a href="javascript:;" class="weui-btn weui-btn_primary tosettle"
                        style="width: 100px;border-radius: 0;">{{btntxt}}</a>
                        {{/if}}
                </div>
            </div>
        </div>
</script>
<script type="text/template" id="modaltemp">
    <div class="weui-panel__bd">
        <a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
            <div class="weui-media-box__hd">
                <img class="weui-media-box__thumb" src="{{selSpecObj.GoodsSpecImg}}" alt="">
            </div>
            <div class="weui-media-box__bd">
                <h4 class="weui-media-box__title"><span class="price">{{selSpecObj.GoodsRetailPrice}}</span>
                    <span class="price2">{{selSpecObj.GoodsMarketPrice}}</span></h4>
                <p class="weui-media-box__desc">请选择：<span>{{selSpecObj.SpecName||"规格"}}</span></p>
            </div>
        </a>
    </div>
    {{each speclist item idx}}
    <h4 class="weui-label-list weui-media-box__title">{{item.SpecName}}</h4>
    <div class="weui-label-list">
        {{each item.list item2 idx2}}
        {{if(item2.selected)}}
        <label class="label f-white bg-green specitem" data-idx={{idx}} data-idx2={{idx2}}>{{item2.SpecItemName}}</label>
        {{else}}
        <label class="label f-gray b-gray specitem"  data-idx={{idx}} data-idx2={{idx2}}>{{item2.SpecItemName}}</label>
        {{/if}}
        {{/each}} 
    </div>
    {{/each}}  
    <div style="height:30px;"></div>
    <a href="javascript:;" class="weui-btn weui-btn_primary confirmspec">确认</a>
</script>

<script>

    lobsterh5.main({
        data: {
            isEditStatus: false,
            btntxt: '结算',
            showModalmask: false,
            list: [],
            num: 0,
            total: 0,
            seletedAll: false,
            checkList: [], //结算选择
            seletedAll2: false,
            checkList2: [], //删除选择 
            selSpecObj: {}, //选择项 
            speclist: [],
            specdetaillist: [],
            userId: localStorage.getItem("userId"),
        },
        //初始化页面
        pageload: function () {
            this.initevent();
            var cartchecklist = localStorage.getItem("cart" + this.data.userId)
            this.data.checkList = cartchecklist ? JSON.parse(cartchecklist) : [];
            this.getcartlist();
            if (lobsterh5.hasLogin()) {
                this.getcartcount();
            }
        },
        getcartcount() {
            var self = this;
            lobsterh5.GET("/lowcode/APP20200616102057595/shop/?fun=mall.getcartcount", {
                userId: localStorage.getItem("userId")
            }).then(res => {
                var cartcount = res.cartcount;
                if (cartcount > 0)
                    $("#cartcount").text(cartcount).show();
            }).catch(res => {
            })
        },
        //初始化事件
        initevent: function () {
            var self = this;
            // $("#cartlist").on("click", "#tomall", function () {
            //     location.href = "../index.html";
            // })
            $("#cartlist").on("click", ".removecart", function () {
                if (self.data.checkList2.length == 0) {
                    $.toast("请选择要删除的商品", "text");
                    return;
                }
                self.removecart();
            })
            $("#cartlist").on("click", ".tosettle", function () {
                if (self.data.checkList.length == 0) {
                    $.toast("请选择要结算的商品", "text");
                    return;
                }
                var filterlist = self.data.list.filter(a => {
                    return self.data.checkList.find(b=>b==a.CartId);
                });
                var goods = [];
                filterlist.forEach(a => {
                    goods.push({
                        ShopId: a.ShopId,
                        ShopName: a.ShopName,
                        GoodsId: a.GoodsId,
                        GoodsName: a.GoodsName,
                        GoodsPrice: a.GoodsRetailPrice,
                        GoodsNum: a.Num,
                        SpecName: a.SpecName,
                        SpecDetailId: a.SpecDetailId,
                        SpecImg: a.GoodsSpecImg
                    })
                })
                location.href = "../settle/index.html?goods=" + JSON.stringify(goods);
            });
            $("#modalcontent").on("click", ".confirmspec", function () {
                self.updatecartspec();
            })
            $(document).on("click", '.weui-count__decrease', function (e) {
                var idx = $(this).parent().data("idx");
                self.changenum(idx, 0);
                var $input = $(e.currentTarget).parent().find('.weui-count__number');
                $input.val(self.data.list[idx].Num);
            })
            $(document).on("click", '.weui-count__increase', function (e) {
                var idx = $(this).parent().data("idx");
                self.changenum(idx, 1);
                var $input = $(e.currentTarget).parent().find('.weui-count__number');
                $input.val(self.data.list[idx].Num);
            })
            $("#cartlist").on("click", ".spec", function () {
                self.getspec($(this).data("item"));
            })
            $("#modalcontent").on("click", ".specitem", function () {
                var idx = $(this).data("idx");
                var idx2 = $(this).data("idx2");
                self.data.speclist[idx].list.forEach(a => {
                    a.selected = false;
                })
                self.data.speclist[idx].list[idx2].selected = true;
                var arr = [];
                self.data.speclist.forEach(a => {
                    var filter = a.list.filter(b => {
                        return b.selected
                    });
                    if (filter != null && filter.length > 0)
                        arr.push(filter[0]);
                })
                if (arr.length == self.data.speclist.length) {
                    var specfilter = self.data.specdetaillist.filter(a => {
                        var speccom = arr.map(n => n.SpecId).sort((a1, a2) => {
                            return a1 - a2;
                        }).join("_");
                        var sepcitemcom = arr.map(n => n.SpecItemId).sort((a1, a2) => {
                            return a1 - a2;
                        }).join("_")
                        return a.SpecCom == speccom && a.SpecItemCom == sepcitemcom;
                    })
                    self.data.selSpecObj.num = 1;
                    if (specfilter != null && specfilter.length > 0) {
                        self.data.selSpecObj.SpecDetailId = specfilter[0].GoodsSpecDetailId;
                        self.data.selSpecObj.SpecName = arr.map(n => n.SpecItemName).join(";");
                        self.data.selSpecObj.GoodsSpecImg = specfilter[0].GoodsSpecImg;
                        self.data.selSpecObj.GoodsRetailPrice = specfilter[0].GoodsRetailPrice;
                        self.data.selSpecObj.GoodsMarketPrice = specfilter[0].GoodsMarketPrice;
                        self.data.selSpecObj.GoodsStock = specfilter[0].GoodsStock;
                        if (self.data.selSpecObj.GoodsStock <= 0)
                            $.toast("商品数量为0", 'text');
                    } else {
                        self.data.selSpecObj.SpecDetailId = 0;
                        $.toast("无此规格", 'text');
                    }
                }
                self.initmodal();
                $("#spectxt").text(self.data.selSpecObj.SpecName);
            })
            $("#cartlist").on("click", ".itemcheckbox", function () {
                if (!self.data.isEditStatus) {
                    self.data.checkList = [];
                    $(".itemcheckbox:checked").each(function () {
                        self.data.checkList.push($(this).data("cartid"));
                    });
                    self.data.list.forEach(a => {
                        if (self.data.checkList.find(b => b == a.CartId))
                            a.checked = true;
                        else
                            a.checked = false;
                    })
                    self.initcheck();
                } else {
                    self.data.checkList2 = [];
                    $(".itemcheckbox:checked").each(function () {
                        self.data.checkList2.push($(this).data("cartid"));
                    });
                    self.data.list.forEach(a => {
                        if (self.data.checkList2.find(b => b == a.CartId))
                            a.checked2 = true;
                        else
                            a.checked2 = false;
                    })
                    var filterlist = self.data.list.filter(a => {
                        return self.data.checkList2.find(b => b == a.CartId);
                    });
                    if (self.data.list.length == filterlist.length)
                        self.data.seletedAll2 = true;
                    else
                        self.data.seletedAll2 = false;
                }
                self.inittemp();
            });
            $("#cartlist").on("click", "#sall", function () {
                if (self.data.list.length == 0)
                    return;
                if (!self.data.isEditStatus) {
                    if (!self.data.seletedAll) {
                        self.data.seletedAll = true
                        self.data.checkList = self.data.list.map(n => n.CartId);
                        self.data.list.forEach(a => {
                            a.checked = true;
                        })
                    } else {
                        self.data.seletedAll = false;
                        self.data.checkList = [];
                        self.data.list.forEach(a => {
                            a.checked = false;
                        })
                    }
                    self.initcheck();
                } else {
                    if (!self.data.seletedAll2) {
                        self.data.seletedAll2 = true
                        self.data.checkList2 = self.data.list.map(n => n.CartId);
                        self.data.list.forEach(a => {
                            a.checked2 = true;
                        })
                    } else {
                        self.data.seletedAll2 = false;
                        self.data.checkList2 = [];
                        self.data.list.forEach(a => {
                            a.checked2 = false;
                        })
                    }
                }
                self.inittemp();
            })
            $("#edit").click(function () {
                var rightText = ''
                self.data.isEditStatus = !self.data.isEditStatus;
                if (self.data.isEditStatus) {
                    rightText = '完成';
                    self.data.btntxt = "删除";
                } else {
                    rightText = '编辑';
                    self.data.btntxt = "结算(" + self.data.num + ")";
                }
                self.inittemp();
            })
        },
        initmodal: function () {
            var html = template("modaltemp", { selSpecObj: this.data.selSpecObj, speclist: this.data.speclist });
            $("#modalcontent").html(html);
        },
        changenum(idx, type) {
            if (type == 0) {
                this.data.list[idx].Num--;
                if (this.data.list[idx].Num < 1)
                    return;
            } else
                this.data.list[idx].Num++;
            if (this.data.list[idx].Num > this.data.list[idx].GoodsStock) {
                $.toast("库存不足", 'forbidden');
                return;
            }
            this.initcheck();
            this.inittemp();
            this.udpatecartnum(this.data.list[idx]);
        },
        getcartlist() {
            var self = this;
            lobsterh5.GET("/lowcode/APP20200616102057595/shop/?fun=mall.getcartlist", {
                userId: self.data.userId,
            }).then(res => {
                self.data.list = res.list;
                if (self.data.list.length > 0 && self.data.checkList) {
                    self.data.list.forEach(a => {
                        if (self.data.checkList.find(b => b == a.CartId))
                            a.checked = true
                        else
                            a.checked = false
                    })
                    self.initcheck();
                }
                self.inittemp();
            }).catch(res => {
                $.toast(res.msg, 'forbidden');
            })
        },
        getspec(item) {
            var self = this;
            self.data.selSpecObj = item;
            lobsterh5.GET("/lowcode/APP20200616102057595/shop/?fun=mall.getspeclist", {
                goodsId: item.GoodsId
            }).then(res => {
                $("#half").popup();//打开 
                self.data.speclist = self.groupArr(res.speclist, "SpecId");
                self.data.specdetaillist = res.specdetaillist;
                var filter = self.data.specdetaillist.filter(a => {
                    return a.GoodsSpecDetailId == item.SpecDetailId
                })
                if (filter != null && filter.length > 0) {
                    var specCom = filter[0].SpecCom;
                    var specItemCom = filter[0].SpecItemCom;
                    self.data.speclist.forEach(a => {
                        a.list.forEach(b => {
                            if (specItemCom.split('_').includes(String(b.SpecItemId)) &&
                                specCom.split('_').includes(String(b.SpecId))) {
                                b.selected = true;
                            }
                        })
                    })
                }
                self.initmodal();
            }).catch(res => {
                $.toast(res.msg, 'forbidden');
            })
        },
        //数组分组
        groupArr(list, field) {
            var fieldList = [],
                att = [];
            list.map((e) => {
                fieldList.push(e[field])
            })
            //数组去重
            fieldList = fieldList.filter((e, i, self) => {
                return self.indexOf(e) == i
            })
            for (var j = 0; j < fieldList.length; j++) {
                //过滤出匹配到的数据
                var arr = list.filter((e) => {
                    return e.SpecId == fieldList[j];
                })
                att.push({
                    SpecId: arr[0].SpecId,
                    SpecName: arr[0].SpecName,
                    list: arr
                })
            }
            return att;
        },
        initcheck: function () {
            localStorage.setItem("cart" + this.data.userId, JSON.stringify(this.data.checkList));
            var filterlist = this.data.list.filter(a => {
                return this.data.checkList.find(b => b == a.CartId);
            });
            if (this.data.list.length == filterlist.length)
                this.data.seletedAll = true;
            else
                this.data.seletedAll = false;
            this.data.num = this.sum(filterlist.map(n => parseInt(n.Num)))
            if (this.data.num > 0) {
                this.data.btntxt = '结算(' + this.data.num + ')';
                this.data.total = this.sum(filterlist.map(n => (parseInt(n.Num) * parseFloat(n.GoodsRetailPrice)))).toFixed(2)
            } else {
                this.data.btntxt = '结算';
                this.data.total = 0;
            }
        },
        sum(arr) {
            var s = 0;
            for (var i = arr.length - 1; i >= 0; i--) {
                s += arr[i];
            } s
            return s;
        },
        inittemp: function () {
            var html = template("cartlisttemp", {
                list: this.data.list,
                isEditStatus: this.data.isEditStatus, total: this.data.total,
                seletedAll: this.data.seletedAll, seletedAll2: this.data.seletedAll2,
                btntxt: this.data.btntxt
            });
            $("#cartlist").html(html);
        },
        udpatecartnum(model) {
            var self = this;
            lobsterh5.POST("/lowcode/APP20200616102057595/shop/?fun=mall.updatecartnum", {
                CartId: model.CartId,
                Num: model.Num
            }).then(res => {

            }).catch(res => {
                $.toast(res.msg, 'forbidden');

            })
        },
        removecart() {
            var self = this;
            $.confirm("您确定要删除吗?", "确认删除?", function () {
                $.showLoading("正在删除")
                lobsterh5.POST("/lowcode/APP20200616102057595/shop/?fun=mall.removecart", {
                    ids: JSON.stringify(self.data.checkList2)
                }).then(res => {
                    $.hideLoading();
                    $.toast("删除成功");
                    self.getcartlist();
                }).catch(res => {
                    $.toast(res.msg, 'forbidden');

                })
            }, function () {
                //取消操作
            });
        },
        updatecartspec: function () {
            var self = this;
            var selSpecObj = self.data.selSpecObj;
            lobsterh5.POST("/lowcode/APP20200616102057595/shop/?fun=mall.updatecartspec", {
                CartId: selSpecObj.CartId,
                SpecDetailId: selSpecObj.SpecDetailId,
                SpecName: selSpecObj.SpecName,
                UserId:localStorage.getItem("userId")
            }).then(res => {
                $.closePopup();
                self.getcartlist();
            }).catch(res => {
                $.toast(res.msg, 'forbidden');

            })
        }
    })
</script>